package com.example.spring5.事务;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration//配置类
@ComponentScan(basePackages = "com.example.spring5.事务")//组件扫描
@EnableTransactionManagement//开启事务
public class 全注解事务配置 {

    @Bean//创建数据库连接池
    public DruidDataSource getDruidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/spring5");
//        druidDataSource.setUrl("jdbc:mysql:///spring");  //同上
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        return druidDataSource;
    }
    @Bean//创建JdbcTemplate对象d
    public JdbcTemplate getJdbcTemplate(javax.sql.DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);//注入数据源  这样不好
//        jdbcTemplate.setDataSource(getDruidDataSource());//注入数据源  这样不好  因为之前创建过了   不需要在创建了
        return jdbcTemplate;
    }
    @Bean //创建事务管理器
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

    @Test
    public void 全注解(){
        ApplicationContext context = new AnnotationConfigApplicationContext(全注解事务配置.class);
        BankService bankService = context.getBean("bankService", BankService.class);
        bankService.accountMoney(100.0);

    }


}
